import { Tab } from '../../../contexts/AppContext';
import { TabManager } from './TabManager';
import { CookieData } from './CookieManager';

export interface BatchExportOptions {
  includeCookies: boolean;
  includeLocalStorage: boolean;
  includeSessionInfo: boolean;
  format: 'json' | 'txt' | 'csv';
  filterByPlatform?: string;
  filterByAccount?: string;
}

export interface BatchExportResult {
  totalTabs: number;
  exportedTabs: number;
  totalCookies: number;
  fileContent: string;
  fileName: string;
  timestamp: string;
}

export interface TabExportData {
  tabId: string;
  url: string;
  title: string;
  accountId?: string;
  platform?: string;
  cookies: CookieData[];
  localStorageCount: number;
  lastActive: string;
}

export class BatchOperations {
  private tabManager: TabManager;

  constructor(tabManager: TabManager) {
    this.tabManager = tabManager;
  }

  // 批量导出所有标签页的Cookie
  async exportAllCookies(
    tabs: Tab[],
    options: BatchExportOptions = {
      includeCookies: true,
      includeLocalStorage: false,
      includeSessionInfo: true,
      format: 'json'
    }
  ): Promise<BatchExportResult> {
    try {
      const exportData: TabExportData[] = [];
      let totalCookies = 0;

      // 收集所有标签页的数据
      for (const tab of tabs) {
        // 应用过滤器
        if (options.filterByPlatform && tab.platform !== options.filterByPlatform) {
          continue;
        }
        if (options.filterByAccount && tab.accountId !== options.filterByAccount) {
          continue;
        }

        const session = this.tabManager.getSession(tab.id);
        if (!session) continue;

        const tabData: TabExportData = {
          tabId: tab.id,
          url: tab.url,
          title: tab.title,
          accountId: tab.accountId,
          platform: tab.platform,
          cookies: options.includeCookies ? session.cookies.getAllCookies() : [],
          localStorageCount: options.includeLocalStorage ? session.localStorage.size : 0,
          lastActive: session.lastActive.toISOString()
        };

        totalCookies += tabData.cookies.length;
        exportData.push(tabData);
      }

      // 生成文件内容
      const fileContent = this.generateFileContent(exportData, options);
      const fileName = this.generateFileName(options);

      const result: BatchExportResult = {
        totalTabs: tabs.length,
        exportedTabs: exportData.length,
        totalCookies,
        fileContent,
        fileName,
        timestamp: new Date().toISOString()
      };

      return result;
    } catch (error) {
      console.error('批量导出失败:', error);
      throw new Error(`批量导出失败: ${error}`);
    }
  }

  // 生成文件内容
  private generateFileContent(exportData: TabExportData[], options: BatchExportOptions): string {
    switch (options.format) {
      case 'json':
        return this.generateJsonContent(exportData, options);
      case 'csv':
        return this.generateCsvContent(exportData, options);
      case 'txt':
        return this.generateTextContent(exportData, options);
      default:
        return this.generateJsonContent(exportData, options);
    }
  }

  // 生成JSON格式内容
  private generateJsonContent(exportData: TabExportData[], options: BatchExportOptions): string {
    const exportPayload = {
      metadata: {
        exportedAt: new Date().toISOString(),
        version: '1.0.0',
        totalTabs: exportData.length,
        totalCookies: exportData.reduce((sum, tab) => sum + tab.cookies.length, 0),
        options
      },
      tabs: exportData.map(tab => ({
        ...tab,
        cookies: options.includeCookies ? tab.cookies : undefined,
        localStorage: options.includeLocalStorage ? 
          Array.from(this.tabManager.getSession(tab.tabId)?.localStorage.entries() || []) : 
          undefined
      }))
    };

    return JSON.stringify(exportPayload, null, 2);
  }

  // 生成CSV格式内容
  private generateCsvContent(exportData: TabExportData[], options: BatchExportOptions): string {
    const lines: string[] = [];
    
    // 标题行
    lines.push('Tab ID,URL,Title,Platform,Account ID,Cookie Count,Last Active');
    
    // 数据行
    for (const tab of exportData) {
      lines.push([
        tab.tabId,
        `"${tab.url}"`,
        `"${tab.title}"`,
        tab.platform || '',
        tab.accountId || '',
        tab.cookies.length,
        new Date(tab.lastActive).toLocaleString()
      ].join(','));
    }

    return lines.join('\n');
  }

  // 生成文本格式内容
  private generateTextContent(exportData: TabExportData[], options: BatchExportOptions): string {
    const lines: string[] = [];
    
    lines.push(`批量导出报告 - ${new Date().toLocaleString()}`);
    lines.push(`标签页数量: ${exportData.length}`);
    lines.push(`Cookie总数: ${exportData.reduce((sum, tab) => sum + tab.cookies.length, 0)}`);
    lines.push('');
    
    for (const tab of exportData) {
      lines.push(`标签页: ${tab.title}`);
      lines.push(`URL: ${tab.url}`);
      lines.push(`平台: ${tab.platform || '未知'}`);
      lines.push(`账号: ${tab.accountId || '未绑定'}`);
      lines.push(`Cookie数量: ${tab.cookies.length}`);
      
      if (options.includeCookies && tab.cookies.length > 0) {
        lines.push('Cookie列表:');
        tab.cookies.forEach(cookie => {
          lines.push(`  ${cookie.name}=${cookie.value} (${cookie.domain})`);
        });
      }
      
      lines.push('');
    }

    return lines.join('\n');
  }

  // 生成文件名
  private generateFileName(options: BatchExportOptions): string {
    const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
    let baseName = `browser_export_${timestamp}`;
    
    if (options.filterByPlatform) {
      baseName += `_${options.filterByPlatform}`;
    }
    if (options.filterByAccount) {
      baseName += `_account`;
    }
    
    switch (options.format) {
      case 'json':
        return `${baseName}.json`;
      case 'csv':
        return `${baseName}.csv`;
      case 'txt':
        return `${baseName}.txt`;
      default:
        return `${baseName}.json`;
    }
  }

  // 批量导入Cookie到特定标签页
  async importCookiesToTabs(
    importData: string,
    targetTabs: Tab[],
    mergeStrategy: 'replace' | 'merge' = 'merge'
  ): Promise<{ successful: number; failed: number; totalCookies: number }> {
    try {
      const parsedData = JSON.parse(importData);
      let successful = 0;
      let failed = 0;
      let totalCookies = 0;

      if (!parsedData.tabs || !Array.isArray(parsedData.tabs)) {
        throw new Error('无效的导入数据格式');
      }

      for (const tabData of parsedData.tabs) {
        const targetTab = targetTabs.find(tab => tab.id === tabData.tabId);
        if (!targetTab) {
          failed++;
          continue;
        }

        const session = this.tabManager.getSession(targetTab.id);
        if (!session) {
          failed++;
          continue;
        }

        try {
          if (mergeStrategy === 'replace') {
            session.cookies.clearAll();
          }

          if (tabData.cookies && Array.isArray(tabData.cookies)) {
            tabData.cookies.forEach((cookie: CookieData) => {
              session.cookies.setCookie(cookie);
              totalCookies++;
            });
          }

          successful++;
        } catch (error) {
          console.error(`导入标签页 ${targetTab.id} 失败:`, error);
          failed++;
        }
      }

      return { successful, failed, totalCookies };
    } catch (error) {
      console.error('批量导入失败:', error);
      throw new Error(`批量导入失败: ${error}`);
    }
  }

  // 批量清除所有标签页的Cookie
  clearAllCookies(tabs: Tab[]): { successful: number; failed: number } {
    let successful = 0;
    let failed = 0;

    for (const tab of tabs) {
      try {
        const session = this.tabManager.getSession(tab.id);
        if (session) {
          session.cookies.clearAll();
          successful++;
        } else {
          failed++;
        }
      } catch (error) {
        console.error(`清除标签页 ${tab.id} 的Cookie失败:`, error);
        failed++;
      }
    }

    return { successful, failed };
  }

  // 获取批量操作统计信息
  getBatchStatistics(tabs: Tab[]): {
    totalTabs: number;
    tabsWithCookies: number;
    totalCookies: number;
    platforms: Record<string, number>;
    accounts: Record<string, number>;
  } {
    const platforms: Record<string, number> = {};
    const accounts: Record<string, number> = {};
    let tabsWithCookies = 0;
    let totalCookies = 0;

    for (const tab of tabs) {
      const session = this.tabManager.getSession(tab.id);
      const cookieCount = session ? session.cookies.getAllCookies().length : 0;
      
      if (cookieCount > 0) {
        tabsWithCookies++;
        totalCookies += cookieCount;
      }

      // 统计平台分布
      if (tab.platform) {
        platforms[tab.platform] = (platforms[tab.platform] || 0) + 1;
      }

      // 统计账号分布
      if (tab.accountId) {
        accounts[tab.accountId] = (accounts[tab.accountId] || 0) + 1;
      }
    }

    return {
      totalTabs: tabs.length,
      tabsWithCookies,
      totalCookies,
      platforms,
      accounts
    };
  }

  // 下载导出文件
  downloadExportFile(result: BatchExportResult): void {
    const blob = new Blob([result.fileContent], { 
      type: this.getMimeType(result.fileName) 
    });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = result.fileName;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
  }

  // 获取MIME类型
  private getMimeType(fileName: string): string {
    if (fileName.endsWith('.json')) return 'application/json';
    if (fileName.endsWith('.csv')) return 'text/csv';
    if (fileName.endsWith('.txt')) return 'text/plain';
    return 'application/octet-stream';
  }
}

// 批量操作管理器
export class BatchOperationsManager {
  private static instance: BatchOperationsManager;
  private batchOps: BatchOperations;

  private constructor() {
    this.batchOps = new BatchOperations(new TabManager());
  }

  static getInstance(): BatchOperationsManager {
    if (!BatchOperationsManager.instance) {
      BatchOperationsManager.instance = new BatchOperationsManager();
    }
    return BatchOperationsManager.instance;
  }

  // 获取批量操作实例
  getBatchOperations(): BatchOperations {
    return this.batchOps;
  }

  // 快速导出所有Cookie（简化接口）
  async quickExportAllCookies(tabs: Tab[]): Promise<void> {
    const result = await this.batchOps.exportAllCookies(tabs, {
      includeCookies: true,
      includeLocalStorage: false,
      includeSessionInfo: true,
      format: 'json'
    });
    
    this.batchOps.downloadExportFile(result);
  }

  // 快速清除所有Cookie（简化接口）
  quickClearAllCookies(tabs: Tab[]): void {
    const { successful, failed } = this.batchOps.clearAllCookies(tabs);
    
    if (failed > 0) {
      alert(`清除完成: ${successful} 个成功, ${failed} 个失败`);
    } else {
      alert(`已成功清除 ${successful} 个标签页的Cookie`);
    }
  }

  // 显示批量操作统计
  showStatistics(tabs: Tab[]): void {
    const stats = this.batchOps.getBatchStatistics(tabs);
    
    const message = [
      `标签页总数: ${stats.totalTabs}`,
      `有Cookie的标签页: ${stats.tabsWithCookies}`,
      `Cookie总数: ${stats.totalCookies}`,
      '',
      '平台分布:',
      ...Object.entries(stats.platforms).map(([platform, count]) => `  ${platform}: ${count} 个标签页`),
      '',
      '账号分布:',
      ...Object.entries(stats.accounts).map(([accountId, count]) => `  ${accountId}: ${count} 个标签页`)
    ].join('\n');

    alert(message);
  }
}